package com.nx.platform.es.bean.modle.sort;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.nx.platform.es.common.utils.MoreMaps;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class SortField {

    private final SortFieldType type;
    private final ImmutableMap<String, ?> config;

    private SortField(SortFieldType type, ImmutableMap<String, ?> config) {
        this.type = type;
        this.config = config;
    }

    public static SortField create(Map<?, ?> settings) {
        String type = MoreMaps.getString(settings, "type");
        Preconditions.checkState(!Strings.isNullOrEmpty(type), "type not found");
        SortFieldType fieldType = SortFieldType.valueOf(type);
        ImmutableMap<String, ?> config = fieldType.getParser().parse(settings);
        return new SortField(fieldType, config);
    }

    public SortBuilder<?> handle(Map<String, Object> params, SortOrder sortOrder) {
        return type.getHandler().handle(config, params, sortOrder);
    }

    public SortFieldType getType() {
        return type;
    }

    public ImmutableMap<String, ?> getConfig() {
        return config;
    }

}
